package cn.com.wxd.service.zookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu系统
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/8/22.
 *
 * @author WangXuDong
 * @version 1.0
 */
public class ZookeeperHelper implements Watcher {
    private static final Logger log = LoggerFactory.getLogger(ZookeeperHelper.class);
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;
    private static ZookeeperHelper zookeeperHelper;
    private static final String ZOOKEEPERCONFIG = "zookeeper-conn.properties";

    public static ZookeeperHelper getInstance() {
        if (zookeeperHelper == null) {
            zookeeperHelper = new ZookeeperHelper();
            zookeeperHelper.getZooKeeper();  //调用一次进行初始化连接
        }
        return zookeeperHelper;
    }

    /**
     * 连接zookeeper
     */
    private void connectZookeeper()
            throws ConfigurationException, IOException, InterruptedException {
        PropertiesConfiguration pcf = new PropertiesConfiguration(ZOOKEEPERCONFIG);

        String hosts = pcf.getString("zookeeper_hosts");
        int sessionTimeout = pcf.getInt("zookeeper_session_timeout");
        log.info("zookeeper is connecting.");
        zooKeeper = new ZooKeeper(hosts, sessionTimeout, this);
        countDownLatch.await(); //等待一个线程中的其他方法执行完毕
    }

    /**
     * 获取ZooKeeper
     *
     * @return
     */
    public ZooKeeper getZooKeeper() {
        if (zooKeeper == null || !zooKeeper.getState().isAlive()) {
            try {
                connectZookeeper();
            } catch (ConfigurationException e) {
                log.error("无法读取配置文件" + ZOOKEEPERCONFIG, e);
            } catch (Exception e) {
                log.error("zookeeper尝试连接失败.", e);
            }
        }
        return zooKeeper;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            log.info("zookeeper is connection success.");
            countDownLatch.countDown(); //连接后释放锁，然后创建好的zookeeper
        }
    }
}
